package com.me.netty.global;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class ChannelSupervise {
    private static final ChannelGroup globalGroup=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static final ConcurrentMap<String, ChannelId> channelMap=new ConcurrentHashMap<>();
    private static final ConcurrentMap<String, String> userMap=new ConcurrentHashMap<>();
    public  static void addChannel(Channel channel,String ext){
        globalGroup.add(channel);
        channelMap.put(channel.id().asShortText(),channel.id());
        userMap.put(channel.id().asShortText(),ext);
    }

    public  static ConcurrentMap<String, String> getUseMap(){
        return userMap;
    }
    public static void removeChannel(Channel channel){
        globalGroup.remove(channel);
        channelMap.remove(channel.id().asShortText());
        userMap.remove(channel.id().asShortText());
    }
    public static  Channel findChannel(String id){
        return globalGroup.find(channelMap.get(id));
    }
    public static void send2All(TextWebSocketFrame tws){
        globalGroup.writeAndFlush(tws);
    }

    public static void send2AllOther(TextWebSocketFrame tws, Channel self){
        globalGroup.writeAndFlush(tws, channel -> !channel.equals(self));
    }
    public static void send2All(BinaryWebSocketFrame tws){
        globalGroup.writeAndFlush(tws);
    }

    public static void main(String[] args) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(new URL("http://hongyuedu.cn/group1/M00/00/0C/wKgAHGesQ0qASL75ABc5oPtTLV8205_150x150.jpg"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "jpg", baos);
//        String base64Data = Base64.getEncoder().encodeToString(baos.toByteArray());
//        System.out.println(base64Data);
//        byte[] decode = Base64.getDecoder().decode(base64Data);
//        String result = new String(decode, StandardCharsets.UTF_8);
//        System.out.println(result);
    }
}
